﻿Imports System.Text
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Windows.Navigation
Imports System.Windows.Shapes
Imports System.Timers
Imports System.ComponentModel

Namespace VsSpeakerCompanion.UI
	''' <summary>
	''' Interaction logic for LoginControl.xaml
	''' </summary>
	Partial Friend Class EndingSessionControl
		Inherits UserControl
		Friend Shared ReadOnly RemainingTimeToCancelEndSessionProperty As DependencyProperty = DependencyProperty.Register("RemainingTimeToCancelEndSession", GetType(Integer), GetType(EndingSessionControl))

        Private Const TimeToCancelEndSession = 5

        Friend Property RemainingTimeToCancelEndSession As Integer
            Get
                Return CInt(Fix(GetValue(RemainingTimeToCancelEndSessionProperty)))
            End Get
            Private Set(ByVal value As Integer)
                SetValue(RemainingTimeToCancelEndSessionProperty, value)
            End Set
        End Property

		Friend Event Comitted As EventHandler
		Friend Event Cancelled As EventHandler
        Private WithEvents timer As Timer

		Friend Sub New()
			InitializeComponent()

			Me.DataContext = Me

			timer = New Timer(1000)
        End Sub

        Private Sub OnTimerElapsed() Handles timer.Elapsed
            Me.Dispatcher.Invoke(New Action(Sub()
                                                TimerElapsedStub()
                                            End Sub))
        End Sub

        Private Sub TimerElapsedStub()
            RemainingTimeToCancelEndSession -= 1
            If RemainingTimeToCancelEndSession = 0 Then
                Me.Stop()
                OnComitted(New EventArgs)
            End If
        End Sub

		''' <summary>
		''' Raises the Comitted event
		''' </summary>
		''' <param name="e"></param>
		Protected Overridable Sub OnComitted(ByVal e As EventArgs)
			RaiseEvent Comitted(Me, e)
		End Sub

		''' <summary>
		''' Raises the Cancelled event
		''' </summary>
		''' <param name="e"></param>
		Protected Overridable Sub OnCancelled(ByVal e As EventArgs)
			RaiseEvent Cancelled(Me, e)
		End Sub

		Friend Sub Start()
			Me.RemainingTimeToCancelEndSession = TimeToCancelEndSession
			Me.timer.Start()
		End Sub

		Friend Sub [Stop]()
			Me.timer.Stop()
		End Sub

		Private Sub OnCancelButtonClick(ByVal sender As Object, ByVal e As RoutedEventArgs)
			Me.Stop()
            OnCancelled(New EventArgs)
		End Sub
	End Class
End Namespace